# -*- coding: utf-8 -*-
"""
@author:
@time: 2024/7/8 11:01 PM
@Function:
"""
import requests
import xlrd
from jira import JIRA


class Read_testcase_excel():
    """
    读取excel中的测试用例
    """
    def __init__(self,file_path,file_sheetname):
        self.file_path = file_path
        self.file_sheetname = file_sheetname

    def get_caselist(self):
        workbook=xlrd.open_workbook(self.file_path)
        sheetname=workbook.sheet_names()
        sheet1=workbook.sheet_by_name(self.file_sheetname)
        #获取行数
        nrows=sheet1.nrows
        ncols=sheet1.ncols
        #获取单元格所在的数据
        caselist=[]
        for h in range(1,nrows):
            case_info=[]
            for l in range(0,ncols):
                data=sheet1.cell(h,l).value
                if len(data):
                    case_info.append(data)
            caselist.append(case_info)
        return caselist





class create_test_case():

    def __init__(self,username,password):
        self.username = username
        self.password = password
        self.jira_path='http://192.168.99.5:8060'

    def jira_info(self):
        jira=JIRA(self.jira_path,auth=(self.username,self.password))
        #获取当前账户下相关项目信息-10703
        print(jira.projects())
        for jira_info in jira.projects():
            print('获取所有项目的key值：{}<=>项目名称：{}：'.format(jira_info,jira_info.name))
        # print(jira.current_user())
        return jira.project('QHDIA').id

    def create_case(self,project_key=None, summary_name=None, issuetype=None, id=None, priority_name=None,module_name=None, labels=None):
        jira = JIRA(server=self.jira_path, auth=(self.username, self.password))
        # 获取当前的登录用户信息,赋予测试用例中的报告人和经办人
        user = jira.current_user()
        # 获取项目信息
        pro = jira.project(project_key)
        # 提取项目id
        proj_id = pro.id
        issue_dict = {
            # 项目id
            'project': {'id': proj_id},
            # 问题标题
            'summary': summary_name,
            # 问题类型
            'issuetype': issuetype,
            # 用例优先级等级  P1-P2-P3-P4
            # 'priority': {'name': priority_name},
            # 模块-jira中测试用例的模块可以不填
            # 'components': [{'name': module_name}],
            # 问题标签-jira中测试用例的标签可以不填
            # 'labels': labels,
            'description': '这是一个描述',
            # 报告者
            'reporter': {"name": user},
            # 经办人
            'assignee': {"name": user},
            'customfield_10105': 326#这里是绑定测试用例sprint，默认现在是sprint：xbase测试计划&用例
        }
        new_issue = jira.create_issue(fields=issue_dict)
        pro_key=new_issue.key
        caseid = new_issue.id
        print("当前用例编号是：",pro_key)
        print('当前用例id是：',caseid)
        return caseid,pro_key

    def get_cookie(self):
        pyload = {
            "os_username": self.username,
            "os_password": self.password,
        }
        res = requests.post(url=self.jira_path, data=pyload, allow_redirects=False)
        content = str(res.headers)
        org = eval(content)
        post_cookie = org["Set-Cookie"]
        # 获取resp_headers的cookie信息
        # print("post请求的cookie信息：",post_cookie)
        res.close()
        return post_cookie



    # def create_step_api(self, tcid, step_num, expect_result):
    def create_step_api(self,pro_key=None,caseid=None,file_path=None,sheet_name=None):
        print('开始写用例-编号为：{}'.format(pro_key))
        json_info={
            "tcId": caseid
        }
        # file_path = r'D:\测试用例\功能测试用例\paas平台项目\304\用户管理列表-优化增加用户头像显示-功能用例.xlsx'
        case_info = Read_testcase_excel(file_path, sheet_name).get_caselist()
        for index,cases in enumerate(case_info):
            json_info["sequenceNumber"] =index+1
            print('用例：{},{}'.format(index+1,cases))
            for ca in range(len(cases)):
                if ca==0:
                    print('--》',ca)
                    json_info['step']="【用例名称：{}】\n【前置条件：{}】\n{}".format(cases[ca],cases[ca+1],cases[ca+2])
                    json_info['expectedResult']=cases[ca+3]
                    print(json_info)
                    url = 'http://192.168.99.5:8060/rest/synapse/1.0/testStep/addTestStep'
                    header = {
                        'Content-Type': 'application/json',
                        'Cookie': self.get_cookie()
                    }
                    jira_res = requests.post(url=url, json=json_info, headers=header)
                    print(jira_res.status_code)
                else:
                    continue
        url1 = 'http://192.168.99.5:8060/rest/synapse/latest/requirementpanel/linkRequirements'
        header1 = {
            'Content-Type': 'application/json',
            'Cookie': self.get_cookie()
        }
        json_info1={
                    "requirementKeys":"'OPEN-13666'",#填写需要绑定的需求
                    "testcaseKey":pro_key,
                    "history":"yes"
                }
        binding_require_res = requests.post(url=url1, json=json_info1,headers=header1)
        print(binding_require_res.status_code)




if __name__ == '__main__':
    #输入测试用例的路径
    file_path = r'D:\测试用例\功能测试用例\xbase平台项目\2024\305\OPEN-13666_产品体验app_openapi_模型管理支持新格式.xlsx'
    #输入jira对应的用户名和密码
    case = create_test_case('jiahui.feng', 'qwer1234')
    #步骤一：先获取项目信息对应的key，拿对应的key去创建对应项目的用例
    # case.jira_info()
    #步骤二：获取到第一步的key后，传入下面对应的project_key,summary_name为用例名称，issuetype指定测试用例类型  TAIBAO  OPEN
    caseid,pro_key = case.create_case(project_key='OPEN',summary_name='产品体验app_openapi_模型管理支持新格式_测试用例',issuetype='测试用例')
    #步骤三：读取excel并创建测试用例
    case.create_step_api(pro_key=pro_key,caseid=caseid,file_path=file_path,sheet_name='case1')

